package com.xiaohai.big_event_system.interceptor;

import com.alibaba.fastjson2.JSON;
import com.xiaohai.big_event_system.common.R;
import com.xiaohai.big_event_system.exception.CustomException;
import com.xiaohai.big_event_system.utils.JwtUtil;
import com.xiaohai.big_event_system.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token = request.getHeader("Authorization");
            // 获取redis中的token
            String redisToken = redisTemplate.opsForValue().get("token_" + token);
            log.info("redisToken:{}", redisToken);
            if (redisToken == null) {
                throw new CustomException("token失效");
            }
            Map<String, Object> map = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(map);
            return true;
        } catch (Exception e) {
            log.info("拦截器异常:{}", e.getMessage());
            response.setStatus(401);
            response.setContentType("text/html;charset=utf-8"); // 解决编码问题(显示的问号)
            response.getWriter().write(JSON.toJSONString(R.error(401, e.getMessage())));
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
